package com.easybuilder.common.config.restTemplate;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate getRestTemplate() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        // 解决401报错时，报java.net.HttpRetryException: cannot retry due to server authentication, in streaming mode
        factory.setOutputStreaming(false);
        factory.setConnectTimeout(2000);
        factory.setReadTimeout(5000);
        RestTemplate restTemplate = new RestTemplate(factory);
        // 这个地方需要配置消息转换器，不然收到消息后转换会出现异常
        restTemplate.getMessageConverters().add(new WxMappingJackson2HttpMessageConverter());
        // 错误处理
        restTemplate.setErrorHandler(new RtErrorHandler());
        return restTemplate;
    }



    public class WxMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {

        public WxMappingJackson2HttpMessageConverter(){
            List<MediaType> mediaTypes = new ArrayList<>();
            // 支持所有数据格式
            mediaTypes.add(MediaType.ALL);
            setSupportedMediaTypes(mediaTypes);
        }
    }


    public class RtErrorHandler extends DefaultResponseErrorHandler {

        @Override
        public boolean hasError(ClientHttpResponse response) throws IOException {
            return super.hasError(response);
        }

        @Override
        public void handleError(ClientHttpResponse response) throws IOException {
            HttpStatus statusCode = HttpStatus.resolve(response.getRawStatusCode());
            // 白名单
            List<HttpStatus> donotDeal = new ArrayList<>();
            // 未授权的响应401不做默认处理，默认处理会报错
            donotDeal.add(HttpStatus.UNAUTHORIZED);
            // 非白名单则处理
            if (!donotDeal.contains(statusCode)) {
                super.handleError(response);
            }
        }

    }


}
